package com.cloud.bc.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.bc.mapper.BcUserGiftsMapper;
import com.cloud.bc.model.domain.UserInfo;
import com.cloud.bc.model.entity.*;
import com.cloud.bc.model.response.AjaxResp;
import com.cloud.bc.model.response.UserGiftCountResponse;
import com.cloud.bc.model.response.UserGiftResponse;
import com.cloud.bc.service.*;
import com.cloud.bc.util.BcUtils;
import com.cloud.common.model.enums.CurrencyTypeEnum;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * 礼物赠送记录
 *
 * @author douhaichao code generator
 * @date 2021-01-13 11:11:21
 */
@Service
@AllArgsConstructor
public class BcUserGiftsServiceImpl extends ServiceImpl<BcUserGiftsMapper, BcUserGifts> implements BcUserGiftsService {
    private final BcSinglesService bcSinglesService;

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public BcUserGifts selectOne(BcUserGifts req) {
        QueryWrapper queryWrapper = new QueryWrapper<BcUserGifts>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<BcUserGifts> selectAll(BcUserGifts req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<BcUserGifts> selectPage(Page page, BcUserGifts req) {
        IPage<BcUserGifts> list = baseMapper.selectPage(
                page,
                new QueryWrapper<BcUserGifts>().setEntity(req));
        return list;
    }

    /**
     * 根据对象查询所有分页数据(模糊查询)     *      * @return
     */
    @Override
    public IPage<BcUserGifts> selectPageByLike(Page page, BcUserGifts req) {
        QueryWrapper queryWrapper = new QueryWrapper();

        if (null != req.getId()) {
            queryWrapper.eq("id", req.getId());
        }

        if (null != req.getUserId()) {
            queryWrapper.eq("user_id", req.getUserId());
        }

        if (null != req.getGiftId()) {
            queryWrapper.eq("gift_id", req.getGiftId());
        }

        if (null != req.getSource()) {
            queryWrapper.eq("source", req.getSource());
        }

        if (null != req.getGiveId()) {
            queryWrapper.eq("give_id", req.getGiveId());
        }

        if (null != req.getCreateTime()) {
            queryWrapper.eq("create_time", req.getCreateTime());
        }

        if (null != req.getUpdateTime()) {
            queryWrapper.eq("update_time", req.getUpdateTime());
        }
        IPage<BcUserGifts> list = baseMapper.selectPage(page, queryWrapper);
        return list;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(BcUserGifts req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public List<UserGiftResponse> getReceiveGift(Page page, Integer userId) {
        List<UserGiftResponse> receiveGift = baseMapper.getReceiveGift(page, userId);
        receiveGift.forEach(item -> {
            item.setAge(bcSinglesService.ageConvert(item.getBirthday()));
        });
        return receiveGift;
    }

    @Override
    public List<UserGiftResponse> getGiveGift(Page page, Integer userId) {
        List<UserGiftResponse> giveGift = baseMapper.getGiveGift(page, userId);
        giveGift.forEach(item -> {
            item.setAge(bcSinglesService.ageConvert(item.getBirthday()));
        });
        return giveGift;
    }

    @Override
    public List<UserGiftCountResponse> getReceiveGiftCount(Integer giveUserId) {
        return baseMapper.getReceiveGiftCount(giveUserId);
    }

    private final BcUsersService bcUsersService;
    private final BcGiftsService bcGiftsService;
    private final BcChatsService bcChatsService;
    private final BcFinancesService bcFinancesService;
    private final BcFinanceRecordsService bcFinanceRecordsService;
    private final BcUtils bcUtils;

    @Transactional
    @Override
    public AjaxResp userGift(HttpServletRequest request, int userId, int giftId) {
        AjaxResp ajaxResp = new AjaxResp();
        UserInfo userInfo = bcUsersService.getUserInfo(request);
        List<BcGifts> bcGifts = bcGiftsService.selectAll(null);

        //过滤出当前礼物
        BcGifts bcGiftsOne = bcGifts.stream().filter(t -> t.getId().equals(giftId)).findFirst().orElse(null);
        if (null == bcGiftsOne) {
            ajaxResp.setCode(301);
            ajaxResp.setMsg("礼物不存在");
            ajaxResp.setSuccess(false);
            return ajaxResp;
        }

        BcUserGifts bcUserGifts = new BcUserGifts();
        bcUserGifts.setUserId(userInfo.getId());
        bcUserGifts.setGiveId(userId);
        bcUserGifts.setGiftId(giftId);
        BigDecimal price = Convert.toBigDecimal(bcGiftsOne.getPrice());
        if (price.compareTo(BigDecimal.ZERO) > 0) {
            //扣除余额
            Integer fromUserId = userInfo.getId();
            Integer toUserId = userId;
            BcFinances bcFinances = new BcFinances();
            bcFinances.setCandyPrice(price);
            bcFinances.setUserId(fromUserId);
            boolean result = bcFinancesService.sub(bcFinances);
            if (!result) {
                ajaxResp.setCode(301);
                ajaxResp.setObj(bcUtils.gotoUrl(request, "/center/account/deposit/candy"));
                ajaxResp.setMsg("余额不足");
                ajaxResp.setSuccess(false);
                return ajaxResp;
            }

            BcFinanceRecords bcFinanceRecords = new BcFinanceRecords();
            bcFinanceRecords.setUserId(fromUserId);
            bcFinanceRecords.setCurrencyType(CurrencyTypeEnum.CANDY.getCode());
            bcFinanceRecords.setType(1);
            //赠送接收人
            bcFinanceRecords.setPid(toUserId);
            bcFinanceRecords.setIncome(NumberUtil.mul(price, -1));
            bcFinanceRecords.setRemark("赠送礼物" + bcGiftsOne.getTitle());
            bcFinanceRecordsService.recodeAdd(bcFinanceRecords);

            //目标人增加余额
            BcFinances bcFinancesGive = new BcFinances();
            bcFinancesGive.setCandyPrice(price);
            bcFinancesGive.setUserId(toUserId);
            bcFinancesService.add(bcFinancesGive);

            BcFinanceRecords bcFinanceRecordsGive = new BcFinanceRecords();
            bcFinanceRecordsGive.setUserId(toUserId);
            bcFinanceRecordsGive.setCurrencyType(CurrencyTypeEnum.CANDY.getCode());
            bcFinanceRecordsGive.setType(2);
            //赠送接收人
            bcFinanceRecordsGive.setPid(fromUserId);
            bcFinanceRecordsGive.setIncome(price);
            bcFinanceRecordsGive.setRemark("收到礼物" + bcGiftsOne.getTitle());
            bcFinanceRecordsService.recodeAdd(bcFinanceRecordsGive);
        }
        //如果是免费的，直接写赠送表
//        bcUserGiftsService.save(bcUserGifts);
        this.save(bcUserGifts);
        //写消息表
        BcChats bcChats = new BcChats();
        bcChats.setUserId(userInfo.getId());
        bcChats.setTargetId(userId);
        //消息 12代表的是礼物
        bcChats.setWordType(12);

        bcChats.setWords("<img class=\"gift_img\" src=\"" + bcGiftsOne.getCover() + "\" /><span  class=\"gift_title\">" + bcGiftsOne.getTitle() + "</span>");
        bcChatsService.save(bcChats);
//        if (count > 0) {
////            是免费的查询是否赠送过
//            int countGive = bcUserGiftsService.count(bcUserGifts);
//            if (countGive > 0) {
//                //如果是免费的只能赠送一次
//                ajaxResp.setMsg("免费礼物只能赠送一次");
//                ajaxResp.setSuccess(false);
//                return ajaxResp;
//            }
//            //免费且未赠送过的
//            bcUserGiftsService.save(bcUserGifts);
//            return ajaxResp;
//        }
        //不是免费的需要扣余额

        return ajaxResp;
    }
}
